<style lang="scss">
</style>

<template>
  <div class="app-container">

    <div style="margin-left:20px">
      <el-form ref="queryForm" label-position="left" label-width="70px" inline size="small" >
        <el-form-item label="系统名称" label-width="86px" >
          <el-select v-model="currentSystemId" filterable style="width: 300px;">
            <el-option v-for="item in systemNameList" :key="item.SystemID" :label="item.SystemName" :value="item.SystemID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="用户组" >
          <el-select v-model="currentUserGroupId" filterable placeholder="请选择用户组">
            <el-option v-for="item in userRoleTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="" >
          <el-button :loading="okloading" type="primary" @click="handleSave">保存</el-button>
        </el-form-item>

        <el-form-item label="" >
          <el-popover
            v-model="visibleCopy"
            placement="top"
            width="180">
            <el-form ref="formCopy" :model="formCopy" :rules="rules" label-position="left" label-width="70px" inline size="small" >
              <el-form-item label="用户组" prop="UserGroup">
                <el-select v-model="formCopy.UserGroup" filterable placeholder="请选择用户组">
                  <el-option v-for="item in userRoleTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visibleCopy = false">取消</el-button>
              <el-button :loading="okloading" type="primary" size="mini" @click="handleCopy">确定</el-button>
            </div>
            <el-button slot="reference">从用户组复制</el-button>
          </el-popover>

        </el-form-item>
        <el-form-item label="" >
          <el-popover
            v-model="visibleCopyAdd"
            placement="top"
            width="180">
            <el-form ref="formCopyAdd" :rules="rules" :model="formCopyAdd" label-position="left" label-width="70px" inline size="small" >
              <el-form-item label="用户组" prop="UserGroup">
                <el-select v-model="formCopyAdd.UserGroup" filterable placeholder="请选择用户组">
                  <el-option v-for="item in userRoleTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visibleCopyAdd = false">取消</el-button>
              <el-button :loading="okloading" type="primary" size="mini" @click="handleCopyAdd">确定</el-button>
            </div>
            <el-button slot="reference">从用户组添加</el-button>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>

    <div>
      <div style="width:250px;float:left;margin:0px 5px;margin-bottom:5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>菜单</span>
          </div>
          <el-tree
            ref="menuTree"
            :data="dataMenuTree"
            :props="defaultProps"
            default-expand-all
            highlight-current
            show-checkbox
            node-key="id"
            @current-change="menuCurrentChange"
            @check-change="menuCheckChange"
            @check="menuCheck"/>
        </el-card>
      </div>
      <div style="width:300px;float:left;margin:0px 5px;margin-bottom:5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>菜单操作权限</span>
          </div>
          <label>默认权限</label>
          <el-table
            v-loading="listLoading"
            :data="listDefault"
            :border="false"
            :stripe="true"
            size="small"
            style="width: 100%;">
            <el-table-column label="模块名称" prop="ModuleName" align="center" min-width="70px"/>
            <el-table-column label="操作名称" prop="OperateName" align="center" min-width="70px"/>
          </el-table>
          <div style="height:10px"/>
          <label>可配置权限</label>
          <el-table
            v-loading="listLoading"
            ref="tableOperate"
            :data="listNeetSet"
            :border="false"
            :stripe="true"
            size="small"
            style="width: 100%;"
            @select="operateSelect"
            @select-all="operateSelect">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="模块名称" prop="ModuleName" align="center" min-width="70px"/>
            <el-table-column label="操作名称" prop="OperateName" align="center" min-width="70px"/>
          </el-table>
        </el-card>
      </div>

    </div>

  </div>
</template>

<script>
import { getList as getSystemNameList } from '@/api/systemName'
import { getUserRoleData } from '@/api/user'
import { getMenuTree, getMenuOperateList } from '@/api/menuOperate'
import { getMeunIDList, getOperateIDList, addOperateAndMenuFromGroup, copyOperateAndMenuFromGroup, updateMeunAndOperate } from '@/api/userGroupOperate'

import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'MenuOperate',
  directives: {
    waves
  },
  filters: {
  },
  data() {
    return {
      okloading: false,
      visibleCopy: false,
      visibleCopyAdd: false,
      formCopy: {
        UserGroup: null
      },
      formCopyAdd: {
        UserGroup: null
      },

      userRoleTypeOptions: null,
      systemNameList: [],
      currentSystemId: null,
      currentUserGroupId: null,
      currentMenuId: null,
      munuIdList: [],
      operateIdList: [],
      dataMenuTree: [],
      defaultExpandedKeys: [],
      listLoading: false,
      menuOperateList: [],
      list: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isChanged: false,
      rules: {
        UserGroup: [{ required: true, message: '不能为空' }]
      }
    }
  },

  computed: {
    listDefault() {
      return this.list.filter(d => d.IsDefault)
    },
    listNeetSet() {
      return this.list.filter(d => !d.IsDefault)
    }
  },
  watch: {
    currentSystemId(newVal, oldVal) {
      this.getMeunAndOperateIDList()
    },
    currentUserGroupId() {
      this.getMeunAndOperateIDList()
    }
  },
  created() {
    // this.getList()
    this.getSystemNameList()

    this.getUserRoleData()
  },
  methods: {
    getUserRoleData() {
      getUserRoleData().then(response => {
        if (response.success) {
          this.userRoleTypeOptions = response.data
          for (var item of this.userRoleTypeOptions) {
            if (item.id === 9) {
              this.currentUserGroupId = 9
              break
            }
          }
          if (this.currentSystemId !== 9 && this.userRoleTypeOptions.length > 0) {
            this.currentSystemId = this.userRoleTypeOptions[0].id
          }
        }
      })
    },
    getSystemNameList() {
      getSystemNameList().then(response => {
        const list = response.data
        this.systemNameList = list
        if (list && list.length > 0) {
          const systemId = list[0].SystemID
          this.currentSystemId = systemId
          this.getMenuTree(systemId)
          this.getMenuOperateList(systemId)
        }
      })
    },
    getMeunAndOperateIDList() {
      if (this.currentSystemId && this.currentUserGroupId) {
        this.getMeunIDList(this.currentSystemId, this.currentUserGroupId)
        this.getOperateIDList(this.currentSystemId, this.currentUserGroupId)
      }
    },
    getMeunIDList(systemId, groupId) {
      this.munuIdList = []
      getMeunIDList(systemId, groupId).then(res => {
        this.munuIdList = res.data
        this.setDefaultTree()
      })
    },
    getOperateIDList(systemId, groupId) {
      this.operateIdList = []
      getOperateIDList(systemId, groupId).then(res => {
        this.operateIdList = res.data
      })
    },
    getMenuTree(systemId) {
      getMenuTree(systemId).then(response => {
        const list = response.data
        const expandedKeys = []
        for (const i of list) {
          expandedKeys.push(i.id)
        }
        this.defaultExpandedKeys = expandedKeys
        this.dataMenuTree = list
        this.setDefaultTree()
      })
    },
    setDefaultTree() {
      if (this.dataMenuTree && this.munuIdList && this.dataMenuTree.length > 0) {
        var selectList = []
        for (const id of this.munuIdList) {
          if (id % 10000 !== 0) {
            selectList.push(id)
          }
        }
        this.$refs.menuTree.setCheckedKeys(selectList)
        this.menuCurrentChange(this.$refs.menuTree.getCurrentNode())
      }
    },
    getMenuOperateList(systemId) {
      getMenuOperateList(systemId).then(response => {
        const list = response.data
        this.menuOperateList = list
      })
    },
    menuCurrentChange(currentData, currentNode) {
      if (currentData && currentData.id) {
        this.currentMenuId = currentData.id
        this.list = this.menuOperateList.filter(item => {
          return item.MenuID === currentData.id
        })
        this.$nextTick(() => {
          this.$refs.tableOperate.clearSelection()
          const selectRows = []
          for (const item of this.list) {
            if (this.operateIdList.indexOf(item.OperateID) >= 0) {
              selectRows.push(item)
              this.$refs.tableOperate.toggleRowSelection(item)
            }
          }
        })
      } else {
        this.currentMenuId = undefined
        this.list = this.menuOperateList.filter(item => {
          return item.MenuID === undefined
        })
      }
    },
    menuCheckChange(currentData, checked) {
      // if (checked) {
      //   const index = this.munuIdList.indexOf(currentData.id)
      //   if (index < 0) {
      //     this.munuIdList.push(currentData.id)
      //   }
      // } else {
      //   const index = this.munuIdList.indexOf(currentData.id)
      //   if (index >= 0) {
      //     this.munuIdList.splice(index, 1)
      //   }
      // }
      // console.log(this.munuIdList)
    },
    menuCheck(checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {
      const list = []
      for (const key of checkedKeys.halfCheckedKeys) {
        list.push(key)
      }
      for (const key of checkedKeys.checkedKeys) {
        list.push(key)
      }
      this.munuIdList = list
    },
    operateSelect(selection, row) {
      for (const item of this.listNeetSet) {
        const index = this.operateIdList.indexOf(item.OperateID)
        if (index >= 0) {
          this.operateIdList.splice(index, 1)
        }
      }
      for (const item of selection) {
        this.operateIdList.push(item.OperateID)
      }
    },
    handleSave() {
      const data = {
        SystemID: this.currentSystemId,
        GroupId: this.currentUserGroupId,
        MunuIdList: this.munuIdList,
        OperateIdList: this.operateIdList
      }
      if (!this.currentSystemId) {
        this.$notify({
          message: '请选择系统',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (!this.currentUserGroupId) {
        this.$notify({
          message: '请选择用户组',
          type: 'error',
          duration: 2000
        })
        return
      }
      this.okloading = true
      updateMeunAndOperate(data).then(() => {
        this.okloading = false
        this.$notify({
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {
        this.okloading = false
      })
    },
    handleCopyAdd() {
      this.$refs['formCopyAdd'].validate((valid) => {
        if (valid) {
          const m = {
            systemId: this.currentSystemId,
            GroupIdFrom: this.formCopyAdd.UserGroup,
            GroupIdTo: this.currentUserGroupId
          }
          this.okloading = true
          addOperateAndMenuFromGroup(m).then((res) => {
            this.okloading = false
            this.visibleCopyAdd = false
            this.getMeunAndOperateIDList()
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleCopy() {
      this.$refs['formCopy'].validate((valid) => {
        if (valid) {
          const m = {
            systemId: this.currentSystemId,
            GroupIdFrom: this.formCopy.UserGroup,
            GroupIdTo: this.currentUserGroupId
          }
          this.okloading = true
          addOperateAndMenuFromGroup(m).then((res) => {
            this.okloading = false
            this.visibleCopy = false
            this.getMeunAndOperateIDList()
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleUpdate(row) {

    },

    handleDelete(row) {

    }

  }
}

</script>
